<?php

use \GatewayWorker\Lib\Gateway;  
require_once dirname(__DIR__) . '/public.class.model.php';
class Server_Timer_Model extends Public_Model
{
	/*
		
	*/
	public function updateTimerID($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];
		//保存timer_id
		$this->updateTimer($room_id, $timer_id);
		
		return true;
	}
	

	public function chooseCardPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];
		$account_id = $data['account_id'];

		$this->writeLog("[$room_id] ($account_id) 15s自动打牌");

		$current_timer_id = $this->queryTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateTimer($room_id, -1);
		} else {
			//timer对不上，返回
			$this->writeLog("function(chooseCardPassive):timer对不上($current_timer_id != $timer_id)"." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$active_user = $this->queryActiveUser($room_id);
		if($active_user != $account_id){
			$this->writeLog("function(chooseCardPassive):未轮到你操作"." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		//更新当前出牌
		$new_card = $this->queryNewCard($room_id);
		$hu_flag = 0;
		$gang_flag = 0;
		if($new_card){
			
			$hu_flag = $this->checkHu($room_id, $account_id, $new_card);
			if($hu_flag){
				$this->showWin($room_id, $account_id);
				return true;
			}
			$gang_flag = $this->checkGang($room_id, $account_id, $new_card);
			if($gang_flag == 1){ //暗杠
				$this->anGangFunc($room_id, $account_id, 1);
				return true;
			} else if($gang_flag == 2){ //加杠
				$this->jiaGangFunc($room_id, $account_id, 1);
				return true;
			}

		} 

		$cards = $this->queryPlayerCard($room_id, $account_id);
		if($new_card){
			$cards[] = $new_card;
			sort($cards);
		}

		$mahjong = Mahjong::instance();
		$card = $mahjong->chooseCardToThrow($cards);

		$success = $this->removePlayerCardToDiscard($room_id, $account_id, $card);
		if($success !== OPT_CONST::SUCCESS)
		{
			return false;
		}
			
		$msg_arr = array(
			'result' => 0,
			'operation' => 'ThrowOutCard',
			'result_message' => "玩家出牌",
			'data' => array(
				'account_id' => $account_id,
				'card'  => $card,
				'is_passive' => 1
				)
			);
		$this->pushMessageToGroup($room_id, $msg_arr);

		$this->writeLog("[$room_id] ($account_id) (被动)打牌($card)");

		if($this->checkPeng($room_id, $account_id, $card)){
			//有人碰杠
		} else {
			$next_account_id = $this->takeTurns($room_id);
			$this->notyUserToChoose($room_id, $next_account_id, $has_new_card = true);
		}
		return true;
	}

	public function pengGangPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];
		$account_id = $data['account_id'];

		$this->writeLog("[$room_id] ($account_id) 10s自动碰杠");

		$current_timer_id = $this->queryTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateTimer($room_id, -1);
		} else {
			//timer对不上，返回
			$this->writeLog("function(pengGangPassive):timer对不上($current_timer_id != $timer_id)"." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$active_user = $this->queryActiveUser($room_id);
		if($active_user != $account_id){
			$this->writeLog("function(pengGangPassive):未轮到你操作"." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$playing_status = $this->queryActiveType($room_id);

		if($playing_status == Game::PlayingStatus_Peng){
			$mahjong = Mahjong::instance();
			$cards = $this->queryPlayerCard($room_id, $account_id);
			$analysis = $mahjong->analysisCard($cards);
			if(count($analysis['pair']) > 2 || 
				count($analysis['pair'])==2&&
				(count($analysis['single'])||count($analysis['singleAC'])||count($analysis['singleAB'])||count($analysis['shunAC'])+count($analysis['shunAB'])>2)){
				//上一个打牌
				$last_user_discard = $this->queryLastUserDiscard($room_id);
				$card = $last_user_discard['last_discard'];
				if(in_array($card, $analysis['pair'])){
					$this->pengFunc($room_id, $account_id, 1);
					return true;
				}
			}

		} else if($playing_status == Game::PlayingStatus_Gang){
			$this->baoGangFunc($room_id, $account_id, 1);
			return true;
		}

		$next_account_id = $this->takeTurns($room_id);
		$this->notyUserToChoose($room_id, $next_account_id, $has_new_card = true);
		return true;
	}

	public function qiangGangPassive($arrData)
	{
		

		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$this->writeLog("[$room_id] 10s自动抢杠");

		$timer_id = $data['timer_id'];

		$current_timer_id = $this->queryTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateTimer($room_id, -1);
		} else {
			//timer对不上，返回
			$this->writeLog("function(qiangGangPassive):timer对不上($current_timer_id != $timer_id)"." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$Redis_Model = Redis_Model::getModelObject();
		$replyArr = array("[roomid]"=>$room_id);

		$DaiQiangGang_Key = strtr(Redis_Const::DaiQiangGang_Key, $replyArr);
		$YiQiangGang_Key = strtr(Redis_Const::YiQiangGang_Key, $replyArr);
		$qiang_array =  $Redis_Model->smembersSet($DaiQiangGang_Key);
		if(count($qiang_array) > 0){

			$Redis_Model->smoveSet($DaiQiangGang_Key, $YiQiangGang_Key, $qiang_array);
			$this->setQiangGang($room_id);

			$loser_id = $this->queryActiveUser($room_id);
			$base_score = $this->queryBaseScore($room_id);
			$card = $this->queryNewCard($room_id);
			foreach ($qiang_array as $account_id) {
				$msg_arr = array(
					'result' => 0,
					'operation' => 'QiangGangHu',
					'result_message' => "抢杠胡",
					'data' => array(
						'account_id' => $account_id,
						'card' => $card,
						'loser_id' => $loser_id,
						'score' => 3 * 2 * $base_score
						)
					);
				$this->pushMessageToGroup($room_id, $msg_arr);

				//抢杠胡实时计分
				$this->balanceQiangScore($room_id, $account_id, $loser_id);
			}

			$this->showWin($room_id, -1);
			$this->writeLog("[$room_id] 抢杠胡结束");
		}
		return true;
	}


	public function clearRoomPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 触发自动清房间");

		$current_timer_id = $this->queryTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateTimer($room_id, -1);
		} else {
			//timer对不上，返回
			$this->writeLog("function(clearRoomPassive):timer对不上($current_timer_id != $timer_id)"." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$clients_of_groupid = Gateway::getClientSessionsByGroup($room_id);
		//判断是否全部人离线
		if(count($clients_of_groupid) > 0)
		{
			$this->writeLog("function(clearRoomPassive):房间($room_id)有人不清理");
			return false;
		}

		$MMYSQL = $this->initMysql();
		$Redis_Model = Redis_Model::getModelObject();
		$replyArr = array("[roomid]"=>$room_id);
		$RoomScore_Key = strtr(Redis_Const::RoomScore_Key, $replyArr);

		$game_num = $this->queryGameNumber($room_id);
		$creator = $this->queryCreator($room_id);


        $MMYSQL = $this->initMysql();
        $creatorInfo = $MMYSQL->row("select * from ".WX_Account." where account_id=".$creator);
        if ($creatorInfo['is_manage_on'] == 1 && $game_num == 0){
            $this->writeLog("function(clearRoomPassive):房间($room_id)开启了俱乐部，并且没有玩过，不清理");
            return false;
        }


		if(Config::Ticket_Mode==2 && $game_num==0 && $creator>0){
			$spend_ticket_count = $this->queryTicketCount($room_id);
			$this->balanceTicket($room_id, $creator, - $spend_ticket_count);
		}
		
		//保存积分榜
		if($game_num > 0){
			$Room_Key = strtr(Redis_Const::Room_Key, $replyArr);
			$round = $Redis_Model->hincrbyField($Room_Key, Redis_Const::Room_Field_GameRound, 1);
			$this->writeLog("[$room_id] 第".($round-1)."轮 结束!");

			$setting = $this->queryRoomSetting($room_id);
			//$round = $setting['ground'];
			$game_info['room_id'] = $room_id;
			$game_info['game_type'] = Game::Game_Type;
			$game_info['dealer_num'] = Config::Dealer_Num;
			$game_info['round'] = $round-1;
			
			$scoreboard = array();
			if(isset($setting['scoreboard']) && $setting['scoreboard']){
				$board_json_str = $setting['scoreboard'];
				$scoreboard = json_decode($board_json_str, true); //转为关联数组
			} else {
				$scoreboard = $Redis_Model->hgetallField($RoomScore_Key);

				//保存积分榜
				if(is_array($scoreboard)){
					$ticket_checked_user = $this->queryTicketCheckedUser($room_id);
					foreach ($scoreboard as $key => $value) {
						if(!in_array($key, $ticket_checked_user)){
							//未扣房卡的用户不显示在积分榜上
							unset($scoreboard[$key]);
						}
					}
					$board_json_str = json_encode($scoreboard);
				} else {
					$scoreboard = array();
					$board_json_str = "";
				}
			}

			$name_board = array();
			foreach ($scoreboard as $account_id => $score) {
				$account_sql = 'select nickname from '.WX_Account.' where account_id ='.$account_id;
				$name = $MMYSQL->single($account_sql);
				$name_board[] = array('name'=>$name, 'score'=>$score, 'account_id'=>$account_id);
			}

			//规则文本
			$rule_text = $this->formatRuleText($room_id);
			$balance_scoreboard = array('time'=>time(), 'scoreboard'=>$name_board,'game_num'=>$game_num);
			$balance_board_json_str = json_encode($balance_scoreboard['scoreboard']);
			$start_time = $this->queryStartTime($room_id);

			$MMYSQL = $this->initMysql();
			$board_array['start_time'] = $start_time;
			$board_array['create_time'] = time();
			$board_array['is_delete'] = G_CONST::IS_FALSE;
			$board_array['game_type'] = Game::Game_Type;  //游戏6 麻将
			$board_array['room_id'] = $room_id;
			$board_array['round'] = $round - 1;
			$board_array['game_num'] = $game_num;
			$board_array['rule_text'] = $rule_text;
			$board_array['board'] = $board_json_str;
			$board_array['balance_board'] = $balance_board_json_str;
			$board_id = $MMYSQL->insertReturnID(Room_Scoreboard,$board_array);

			//保存用户积分
			$game_info['score_board'] = $scoreboard;
			$this->saveAccountGameScore($game_info);
		}

		//清理房间
		$this->clearRoom($room_id);

		return true;
	}

	public function breakRoomPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 触发三分钟自动解散房间");

		$current_timer_id = $this->queryTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateTimer($room_id, -1);
		} else {
			//timer对不上，返回
			$this->writeLog("function(breakRoomPassive):timer对不上($current_timer_id != $timer_id)"." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$clients_of_groupid = Gateway::getClientSessionsByGroup($room_id);
		//判断是否全部人离线
		if(count($clients_of_groupid) > 0)
		{
			$this->writeLog("[$room_id] 房间有人也解散房间");

			$msg_arr = array("result"=>"0","operation"=>"BreakRoom","data"=>array('room_id'=>$room_id),"result_message"=>"解散房间");
			$this->pushMessageToGroup($room_id, $msg_arr);

		} else {

		}

		$Redis_Model = Redis_Model::getModelObject();
		$replyArr = array("[roomid]"=>$room_id);
		$RoomScore_Key = strtr(Redis_Const::RoomScore_Key, $replyArr);

		$game_num = $this->queryGameNumber($room_id);
		$creator = $this->queryCreator($room_id);

		if(Config::Ticket_Mode==2 && $game_num==0 && $creator>0){
			$spend_ticket_count = $this->queryTicketCount($room_id);
			$this->balanceTicket($room_id, $creator, - $spend_ticket_count);
		}
		
		//保存积分榜
		if($game_num > 0){
			$Room_Key = strtr(Redis_Const::Room_Key, $replyArr);
			$round = $Redis_Model->hincrbyField($Room_Key, Redis_Const::Room_Field_GameRound, 1);
			$this->writeLog("[$room_id] 第".($round-1)."轮 结束!");

			$setting = $this->queryRoomSetting($room_id);
			//$round = $setting['ground'];
			$game_info['room_id'] = $room_id;
			$game_info['game_type'] = Game::Game_Type;
			$game_info['dealer_num'] = Config::Dealer_Num;
			$game_info['round'] = $round-1;
			
			$scoreboard = array();
			if(isset($setting['scoreboard']) && $setting['scoreboard']){
				$board_json_str = $setting['scoreboard'];
				$scoreboard = json_decode($board_json_str, true); //转为关联数组
			} else {
				$scoreboard = $Redis_Model->hgetallField($RoomScore_Key);

				//保存积分榜
				if(is_array($scoreboard)){
					$ticket_checked_user = $this->queryTicketCheckedUser($room_id);
					foreach ($scoreboard as $key => $value) {
						if(!in_array($key, $ticket_checked_user)){
							//未扣房卡的用户不显示在积分榜上
							unset($scoreboard[$key]);
						}
					}
					$board_json_str = json_encode($scoreboard);
				} else {
					$scoreboard = array();
					$board_json_str = "";
				}
			}

			$MMYSQL = $this->initMysql();
			$name_board = array();
			foreach ($scoreboard as $account_id => $score) {
				$account_sql = 'select nickname from '.WX_Account.' where account_id ='.$account_id;
				$name = $MMYSQL->single($account_sql);
				$name_board[] = array('name'=>$name, 'score'=>$score, 'account_id'=>$account_id);
			}

			//规则文本
			$rule_text = $this->formatRuleText($room_id);
			$balance_scoreboard = array('time'=>time(), 'scoreboard'=>$name_board,'game_num'=>$game_num);
			$balance_board_json_str = json_encode($balance_scoreboard['scoreboard']);

			$start_time = $this->queryStartTime($room_id);

			$board_array['start_time'] = $start_time;
			$board_array['create_time'] = time();
			$board_array['is_delete'] = G_CONST::IS_FALSE;
			$board_array['game_type'] = Game::Game_Type;  //游戏6 麻将
			$board_array['room_id'] = $room_id;
			$board_array['round'] = $round - 1;
			$board_array['game_num'] = $game_num;
			$board_array['rule_text'] = $rule_text;
			$board_array['board'] = $board_json_str;
			$board_array['balance_board'] = $balance_board_json_str;
			$board_id = $MMYSQL->insertReturnID(Room_Scoreboard,$board_array);

			//保存用户积分
			$game_info['score_board'] = $scoreboard;
			$this->saveAccountGameScore($game_info);
		}

		//清理房间
		$this->clearRoom($room_id);

		return true;
	}

}